import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
export class CommonAxios {
	instance
	constructor(config: AxiosRequestConfig) {
		this.instance = axios.create(config)
		this.request()
		this.response()
	}

	// 请求拦截
	private request() {
		this.instance.interceptors.request.use(
			config => {
				const { headers } = config
				headers['token'] = localStorage.getItem('token')
				return config
			},
			error => {
				return Promise.reject(error)
			}
		)
	}

	//响应拦截
	private response() {
		this.instance.interceptors.response.use(
			response => {
				const { data } = response
				if (data.code == '000000') {
					return data
				}
				ElMessage.warning(data.message)
				return Promise.reject(data)
			},
			error => {
				return Promise.reject(error)
			}
		)
	}
}
